<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-menu
          menu-trigger="click"
          active-text-color="#ff8200"
          :default-active="activeIndex"
          mode="horizontal"
          @select="selectArticleCate"
        >
          <el-menu-item index="0">综合</el-menu-item>
          <el-menu-item
            :index="String(v.id)"
            v-for="v in articleCateList"
            :key="v.id"
            >{{ v.label }}</el-menu-item
          >
        </el-menu>
      </el-col>
    </el-row>

    <el-scrollbar ref="scrollbar"
      ><ArticleDetailList
        :articleList="articleList"
        @operateArticle="operateArticle"
        @focusArticle="focusArticle"
        @giveComment="giveComment"
        :parentComponent="0"
      ></ArticleDetailList
    ></el-scrollbar>
  </div>
</template>

<script>
import ArticleDetailList from "./articledetail/ArticleDetailList.vue";
import { mapState, mapMutations, mapActions } from "vuex";
export default {
  components: {
    ArticleDetailList,
  },
  computed: {
    // 文章分类的数据列表
    ...mapState("m_system", ["articleCateList"]),
  },
  watch: {
    // 被选中的文章分类下标
    // articleCateList() {
    //   this.activeIndex = String(this.articleCateList[0].id);
    // },
  },
  data() {
    return {
      activeIndex: sessionStorage.getItem("mainIndex") || "0",
      categoryItem: [
        {
          title: "全部",
          index: "0",
        },
        {
          title: "体育",
          index: "1",
        },
        {
          title: "新闻",
          index: "2",
        },
      ],
      // 文章数据列表
      // 查询参数对象
      queryInfo: {
        // show-按时间 view-按访问量 like-点赞量 collection-收藏量 null-按照label分类
        type: "show",
        page: 1,
        limit: 10,
        // 文章分类
        label: -1,
      },
      // 文章列表
      articleList: [],
      // 文章是否获取完
      isAllArticle: false,
    };
  },
  async created() {
    // 获取文章分类的数据列表
    if (this.articleCateList.length <= 0) await this.getArticleCatList();
    // 获取文章列表数据
    this.getArticleList();
    // 判断是否是注册激活时跳转到的 ?code=%7B"msg"%3A"注册超时","code"%3A402%7D
    if (this.$route.query.code) {
      let res = JSON.parse(this.$route.query.code);
      this.showRegisterInfo(res.code);
    }

    // this.isRegister =
  },
  mounted() {
    // 滚动条滚动事件(分页获取文章)
    this.$refs.scrollbar.handleScroll = () => {
      var wrap = this.$refs.scrollbar.wrap;
      this.$refs.scrollbar.moveY = (wrap.scrollTop * 100) / wrap.clientHeight;
      this.$refs.scrollbar.moveX = (wrap.scrollLeft * 100) / wrap.clientWidth;
      let poor = wrap.scrollHeight - wrap.clientHeight;
      if (wrap.scrollTop === 0) {
        console.log("下拉刷新");
      }
      if (
        poor == parseInt(wrap.scrollTop) ||
        poor == Math.ceil(wrap.scrollTop) ||
        poor == Math.floor(wrap.scrollTop)
      ) {
        console.log("触底");
        // 获取文章列表数据
        if (!this.isAllArticle) {
          this.queryInfo.page++;
          this.getArticleList();
        }
      }
    };
  },
  methods: {
    ...mapActions("m_system", ["getArticleCatList"]),
    // 获取文章列表数据
    async getArticleList() {
      const { code, msg, result } = await this.$http.get("/api/tweet/type", {
        params: this.queryInfo,
      });
      if (code != 200) {
        return this.$showMsg({ msg: "获取文章数据列表失败！", type: "error" });
      }
      let articleList = result.list;
      // 文章获取完毕
      if (articleList.length < this.queryInfo.limit) {
        this.isAllArticle = true;
      }
      // 未登录不获取用户的点赞状态
      if (!localStorage.access_token) {
        this.articleList = [...this.articleList, ...articleList];
        return;
      }
      if (articleList.length == 0) {
        this.articleList = [...this.articleList, ...articleList];
        return;
      }

      // 获取文章是否被该用户点赞
      let articleIdList = articleList.map((v) => v.id);
      let result1 = await this.$http({
        url: "/api/tweet/user_action_status",
        type: "get",
        params: { aid: articleIdList },
      });
      if (result1.code != 200) {
        result1 = await this.$http({
          url: "/api/tweet/user_action_status",
          type: "get",
          params: { aid: articleIdList },
        });
      }
      console.log(result1.result, "给文章添加点赞 收藏 分享 数据");
      //  给文章添加点赞 收藏 分享 数据(用户是否点赞\收藏\分享)
      result1.result.forEach((v, i) => {
        articleList[i].collection = v.collection;
        articleList[i].like = v.like;
        articleList[i].share = v.share;
        articleList[i].focus = v.relation;
      });
      this.articleList = [...this.articleList, ...articleList];
      console.log("文章数据", this.articleList);
    },

    // 获取文章分类的点击事件
    selectArticleCate(index) {
      // console.log(index);
      this.activeIndex = index;
      this.queryInfo.label = index;
      this.queryInfo.type = "-1";
      this.queryInfo.page = 1;
      this.isAllArticle = false;
      if (index == "0") this.queryInfo.type = "show";
      // 获取文章列表数据
      console.log(this.queryInfo);
      this.articleList = [];
      this.getArticleList();
    },

    // 点赞 收藏 分享 操作文章
    operateArticle(method, type, id) {
      console.log(method, type, id);
      // 更新点赞、收藏、关注
      let index = this.articleList.findIndex((v) => v.id == id);
      this.articleList[index][type] = !this.articleList[index][type];
      // 更新点赞、收藏、关注数量
      let num = 1;
      if (method == "add") {
        num = 1;
      } else {
        num = -1;
      }
      if (type == "like") {
        this.articleList[index]["likeCount"] += num;
      } else if (type == "collection ") {
        this.articleList[index]["collectionCount"] += num;
      }
      return this.$showMsg({ msg: "操作成功！", type: "success" });
    },

    // 关注、取消关注博主
    focusArticle(userId) {
      this.articleList.forEach((v) => {
        if (v.userId == userId) {
          v.focus = !v.focus;
        }
      });
    },

    // 添加评论
    giveComment(commentForm) {
      console.log("添加评论");
    },

    // 展示是否注册成功
    showRegisterInfo(code) {
      let msg = code == 200 ? "激活成功！" : "激活失败！";
      this.$alert(msg, "账号状态", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (code == 200) {
            this.$showMsg({
              type: "success",
              msg: "请前去登录！",
            });
          } else {
            this.$showMsg({
              type: "success",
              msg: "请重新注册！",
            });
          }
          // 跳转到首页
          this.$router.push({ query: {} });
        },
      });
    },
  },
};
</script>

<style scoped lang="less">
</style>